<template>
  <div class='u-attrForm'>
    <el-form :inline='true' class='form'>
      <el-form-item class='createTheFormItem' v-for='(attr, attrIndex) in attrList' :key='attr.id' :label='attr.name + "："'  >
        <!-- 选择分类 -->
        <div v-if='attr.value_type === "0"' class='form-selectList' :class='attr.is_require === "1" ? "" : "autoAttr"'>
          <el-checkbox-group v-model="attr.selects">
            <el-checkbox v-for='classItem in attr.classes'
              :key='classItem.id' :label="classItem.id">
              <span>{{ classItem.name }}</span>
              <!-- 再显示子分类 -->
              <el-select v-if='classItem.child && classItem.child.length'
                v-model='classItem.selects'
                multiple collapse-tags clearable
              >
                <el-option
                  v-for='(item) in classItem.child'
                  :key='item.id'
                  :label='item.name'
                  :value='item.id'
                />
              </el-select>
            </el-checkbox>
          </el-checkbox-group>
          <i v-if='attr.is_require !== "1"' class='el-icon-close' @click='closeAutoAttr(attrIndex)'></i>
        </div>
        <!-- 输入类型 -->
        <div v-else  :class='attr.is_require === "1" ? "" : "autoAttr"'>
          <el-input :class='attr.is_require === "1" ? "form-content" : ""' type='text' v-model.trim='attr.classes[0].name' />
          <i v-if='attr.is_require !== "1"' class='el-icon-close' @click='closeAutoAttr(attrIndex)'></i>
        </div>
      </el-form-item>
    </el-form>
    <attr-list :limitCreateNum='1'
      :isShowSelectBox='false'
      :isShowBtn='false'
      ref='attrList' :aType='aType || type' @getSku='getSku'
    />
  </div>
</template>

<script>
import AttrList from '@/components/business/List'
import { setAttrData, createSkus, getChangeAttrs, formatDetailDataToAttrList, contactAttrData as $contactAttrData } from '@/util/formatAttr'

export default {
  name: 'u-attr_form',

  props: ['type', 'aType'],

  components: {
    AttrList
  },

  data() {
    return {
      attrList: [],
      cacheList: []
    }
  },

  methods: {
    $formatDetail(data) {
      // 根据必须和非必须，进行分开格式化
      this.formatInfoData(data.attrs.filter(v => v.is_require === '1'))
      this.contactAttrData()
      this.$refs.attrList.formatDetailDataToAttrList(data.attrs.filter(v => v.is_require !== '1'))
    },
    /**
     * 格式化属性分类数据（全部）
     * 只渲染 is_require === '1' 的数据（必须的）
     * @param {Object} data 属性分类数据
     */
    $formatAttrAndClassData(data) {
      // 生成属性列表
      const tmp = []
      data.forEach(v => {
        if (v.is_require === '0') return false
        tmp.push(setAttrData(v))
      })
      // 生成 sku
      this.attrList = createSkus(tmp)
    },

    // 格式化参数
    $formatOutputData() {
      return getChangeAttrs(this.attrList)
    },

    /**
     * 格式化详情,必须的属性数据
     * 只生成简单的 sku 数据结构
     * 包含 属性 id，已选的分类，已选的子级分类，分类的 id
     * @param {Array<object>} data attrList 属性数组
     */
    formatInfoData(data) {
      const attrTmp = formatDetailDataToAttrList(data)
      this.cacheList = attrTmp
    },

    /**
     * 将 attrList 和 cacheList 数据合并
     * 以 attrList 为底，将 selects 填充
     */
    contactAttrData() {
      this.attrList = $contactAttrData(this.attrList, this.cacheList)
      console.log('必选：', this.attrList)
      this.cacheList = []
    },

    /**
     * 组件通知父级，skuData 数据更新。进行生成数据结构
     * @param {Object} skuData sku 数据集合
     */
    getSku(skuData) {
      // 将 sku 添加到 attrList 列表里
      console.log('skudata:', skuData)
      console.log('attrList', this.attrList)
      const cacheArr = []
      // 把 attrList 和 skuData 相同 id 的属性和 attrList 必须的抽出来
      this.attrList = this.attrList.filter(v => {
        if (v.is_require === '1') return true
        return skuData.some((item) => {
          if (v.id === item.value) {
            cacheArr.push(item.value)
            return true
          }
        })
      })
      // 将有 skuId 的去除，再添加
      skuData.forEach((v) => {
        if (cacheArr.includes(v.value)) return false
        const { value } = v
        this.attrList.push({
          ...v,
          skuId: value
        })
      })
    },

    closeAutoAttr(index) {
      let _i = index
      this.attrList.forEach((v, i) => {
        if (i < index && !v.skuId) _i -= 1
      })
      this.$refs.attrList.closeSku(_i)
    },

    $openSelectAttrBox() {
      this.$refs.attrList.openSelectAttrBox()
    },

    $openCreateAttrBox() {
      this.$refs.attrList.openCreateAttrBox()
    },

    $clear() {
      this.attrList.forEach(v => {
        if (v.type === 1) {
          v.classes[0].name = ''
          v.classes[0].id = ''
        } else {
          if (v.value_type === '1' || v.value_type === '2') {
            v.classes[0].name = ''
            v.classes[0].id = ''
          } else {
            console.log(v)
            v.selects = []
            v.classes.forEach(v2 => {
              v2.selects = []
            })
          }
        }
      })
    }
  }
}
</script>

<style lang='less'>
.u-attrForm {
  .autoAttr {
    display: flex;
    align-items: center;
    .el-cascader, .el-input {
      flex: 1;
      margin-right: 15px;
    }
  }
  .form {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
    &-selectList {
      display: flex;
    }
    .el-form-item__content {
      flex: 1;
    }
  }
  .createTheFormItem {
    display: flex;
    align-items: center;
    width: 50%;
    margin-right: 0;
    .el-form-item__label {
      width: 120px;
    }
    .el-checkbox-group {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      flex: 1;
    }
    .el-checkbox {
      // flex: 1;
      display: flex;
      align-items: center;
      padding-right: 10px;
      box-sizing: border-box;
      margin-bottom: 10px;
      &:nth-child(n+3) {
        // padding-top: 10px;
      }
    }
    .el-checkbox+.el-checkbox {
      margin-left: 0;
      // margin-top: 10px;
    }
  }
}
</style>
